package com.sgj.common.domain.service.impl;

import com.sgj.entity.User;
import com.sgj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author 沈国纪
 * @date 2021/12/18 23:50
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userService.findByName(username);

		if (Objects.isNull(user)) {
			throw new RuntimeException("用户不存在");
		}
		List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
		return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), auths);
	}
}
